﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Windows.Navigation;
using BitcoinMarket.DataConnectors;
using System.Collections.ObjectModel;
using BitcoinMarket.ViewModels;
using Microsoft.Phone.Shell;
using Telerik.Windows.Controls;
using BitcoinMarket.Resources;
using System.ComponentModel;
using System.Threading;
using BitcoinMarket.Libs;

namespace BitcoinMarket
{
    public partial class NetworkStatusChartDetail : PhoneApplicationPage
    {
        public NetworkStatusChartDetail()
        {
            InitializeComponent();
        }

        private string pageTitle = "";
        private string pageURL = "";
        public bool DataLoaded = false;
        public int chartIndex = 0;
        public string chartKeyName = "";
        private Collection<BlockChainChartItem> ChartsAllData = null;

        /// <summary>
        /// When page is navigated to set data context to selected item in list
        /// </summary>
        /// <param name="e"></param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            //Set data to show
            string selectedIndex = "";
            string keyName = "";
            if (NavigationContext.QueryString.TryGetValue("selectedItem", out selectedIndex))
            {
                this.chartIndex = int.Parse(selectedIndex);

                BlockChainChartItem CData = this.GetChartData(this.chartIndex);

                if (CData != null)
                {
                    this.pageURL = "/NetworkStatusChartDetail.xaml?src=tile&itemKey=" + CData.KeyName;
                    this.setViewModel(CData);
                    
                    this.pageTitle = CData.ChartTitle;
                }
            }
            else if (NavigationContext.QueryString.TryGetValue("itemKey", out keyName))
            {
                SystemTray.ProgressIndicator = new ProgressIndicator();
                
                SystemTray.ProgressIndicator.IsIndeterminate = true;
                SystemTray.ProgressIndicator.Text = AppResources.LoadingChartData;
                SystemTray.ProgressIndicator.IsVisible = true;
                //ApplicationBar.Mode = ApplicationBarMode.Minimized;

                this.DataLoaded = false;

                this.chartKeyName = keyName;

                BackgroundWorker worker = new BackgroundWorker();
                worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
                worker.DoWork += new DoWorkEventHandler(worker_DoWork);
                worker.RunWorkerAsync();
            }
        }

        public void setViewModel(BlockChainChartItem CData)
        {
            NetworkStatusChartDetailViewModel vm = new NetworkStatusChartDetailViewModel();
            vm.ChartName = CData.ChartTitle;
            vm.ChartData = CData.Data;
            vm.YAxisTitle = CData.YAxistitle;
            vm.ChartDescription = CData.ChartDescription;
            vm.Min = CData.Min;
            vm.Max = CData.Max;
            
            this.DataContext = vm;
        }

        public void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            this.DataLoaded = true;

            BlockChainChartItem CData = this.GetChartOnlyData();

            if (CData != null)
            {
                this.setViewModel(CData);
            }
            else
            {
                MessageBox.Show(AppResources.chartDataDownloadError);
                foreach (var Btn in ApplicationBar.Buttons)
                {
                    ((ApplicationBarIconButton) Btn).IsEnabled = false;
                }
            }


            SystemTray.ProgressIndicator.IsVisible = false;
        }

        public void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            this.LoadNetworkDataByKeyName(this.chartKeyName);

            while (this.ChartsAllData == null)
            {
                Thread.Sleep(400);
            }
        }

        /// <summary>
        /// Loads the data shown in the "Network info" control
        /// </summary>
        public void LoadNetworkDataByKeyName(string key)
        {
            BlockChainDataConnector dc = new BlockChainDataConnector();
            dc.GetUserSelectedData(NetworkStatusChartsDataDownloaded, key);
        }

        /// <summary>
        /// Callback for the Hash Rate downloaded method
        /// </summary>
        /// <param name="data"></param>
        private void NetworkStatusChartsDataDownloaded(Collection<BlockChainChartItem> ChartsData)
        {
            this.ChartsAllData = ChartsData;
        }

        private BlockChainChartItem GetChartData(int index)
        {
            if (App.ChartsAllData != null)
            {
                this.DataLoaded = true;
                return App.ChartsAllData.ElementAt(index);
            }
            else
            {
                return null;
            }
        }

        private BlockChainChartItem GetChartOnlyData()
        {
            if (this.ChartsAllData.Count > 0)
            {
                this.DataLoaded = true;
                return this.ChartsAllData.ElementAt(0);
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// Navigate to the About page
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ApplicationBarMenuItem_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/AboutPage.xaml", UriKind.Relative));
        }

        /// <summary>
        /// Hide unnecessary items on landscape mode
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PhoneApplicationPage_OrientationChanged(object sender, OrientationChangedEventArgs e)
        {
            PageOrientation orientation = e.Orientation;

            if ((orientation & PageOrientation.Landscape) == PageOrientation.Landscape)
            {
                PageTitle.Visibility = Visibility.Collapsed;

                // TradesHorizontalAxis.ShowLabels = false;
            }
            else if ((orientation & PageOrientation.Portrait) == PageOrientation.Portrait)
            {
                PageTitle.Visibility = Visibility.Visible;

                //TradesHorizontalAxis.ShowLabels = true;
            }
        }

        private void ApplicationBarMenuItem_Click_1(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/AppSettingsPage.xaml", UriKind.Relative));
        }

        /// <summary>
        /// Pin a secondary tile linking to the current page to start
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ApplicationBarIconButton_Click(object sender, EventArgs e)
        {
           /* if (App.isTargetedVersion)
            {
                // Get the new FlipTileData type.
                Type flipTileDataType = Type.GetType("Microsoft.Phone.Shell.FlipTileData, Microsoft.Phone");

                // Get the ShellTile type so we can call the new version of "Update" that takes the new Tile templates.
                Type shellTileType = Type.GetType("Microsoft.Phone.Shell.ShellTile, Microsoft.Phone");

                // Loop through any existing Tiles that are pinned to Start.
                var tileToUpdate = ShellTile.ActiveTiles.First();


                // Get the constructor for the new FlipTileData class and assign it to our variable to hold the Tile properties.
                var UpdateTileData = flipTileDataType.GetConstructor(new Type[] { }).Invoke(null);

                // Set the properties. 
                SetProperty(UpdateTileData, "Title", "Main Tile Title");
                SetProperty(UpdateTileData, "Count", 12);
                SetProperty(UpdateTileData, "BackTitle", "Back Tile Title");
                SetProperty(UpdateTileData, "BackContent", "Content For back tile.");
                SetProperty(UpdateTileData, "SmallBackgroundImage", new Uri("wp8_small.png", UriKind.Relative));
                SetProperty(UpdateTileData, "BackgroundImage", new Uri("wp8_medium.png", UriKind.Relative));
                SetProperty(UpdateTileData, "BackBackgroundImage", new Uri("wp8_back_medium.png", UriKind.Relative));
                SetProperty(UpdateTileData, "WideBackgroundImage", new Uri("wp8_large.png", UriKind.Relative));
                SetProperty(UpdateTileData, "WideBackBackgroundImage", new Uri("wp8_back_large.png", UriKind.Relative));
                SetProperty(UpdateTileData, "WideBackContent", "Content for Wide Back Tile. Lots more text here.");

                // Invoke the new version of ShellTile.Update.
                shellTileType.GetMethod("Update").Invoke(tileToUpdate, new Object[] { UpdateTileData });

                
            }
            else
            {*/
                StandardTileData tileData = new StandardTileData
                {
                    Title = this.pageTitle,
                    BackTitle = AppResources.AppTileTitle,
                    BackgroundImage = new Uri("/Images/SecondTileChart.png", UriKind.Relative),
                    BackBackgroundImage = new Uri("/Images/SecondTileChartFull.png", UriKind.Relative),
                    BackContent = " ",
                };

                Uri tileUri = new Uri(this.pageURL, UriKind.Relative);

                ShellTile.Create(tileUri, tileData);
            /*}*/
        }

        /// <summary>
        /// Show/hide the info layer over the chart
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ApplicationBarIconButton_Click_1(object sender, EventArgs e)
        {
            this.InfoLayer.IsOpen = !this.InfoLayer.IsOpen;
        }

          
        private static void SetProperty(object instance, string name, object value)
        {
          var setMethod = instance.GetType().GetProperty(name).GetSetMethod();
          setMethod.Invoke(instance, new object[] { value });
        }

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            SystemTray.IsVisible = true;
            SystemTray.Opacity = 0;
            SystemTray.ForegroundColor = Colors.White;

            this.BuildLocalizedApplicationBar();
        }
         
        /**
         * Builds the application Bar with translations
         */
        private void BuildLocalizedApplicationBar()
        {
            ApplicationBar = new ApplicationBar();
            ApplicationBar.ForegroundColor = Colors.Black;
            ApplicationBar.BackgroundColor = ColorTools.GetColorFromHexa("#FFD8D8D8");

            ApplicationBarIconButton appBarIconReload = new ApplicationBarIconButton(new Uri("/Images/MB_0001_pin.png", UriKind.Relative));
            appBarIconReload.Text = AppResources.PinToStart;
            appBarIconReload.Click += this.ApplicationBarIconButton_Click;
            ApplicationBar.Buttons.Add(appBarIconReload);

            ApplicationBarIconButton appBarIconInfo = new ApplicationBarIconButton(new Uri("/Images/MB_0011_info3.png", UriKind.Relative));
            appBarIconInfo.Text = AppResources.Info;
            appBarIconInfo.Click += this.ApplicationBarIconButton_Click_1;
            ApplicationBar.Buttons.Add(appBarIconInfo);

            ApplicationBarMenuItem appBarItemSettings = new ApplicationBarMenuItem(AppResources.SettingMenuItem);
            appBarItemSettings.Click += this.ApplicationBarMenuItem_Click_1;
            ApplicationBar.MenuItems.Add(appBarItemSettings);

            ApplicationBarMenuItem appBarItemAbout = new ApplicationBarMenuItem(AppResources.AboutMenuItem);
            appBarItemAbout.Click += this.ApplicationBarMenuItem_Click;
            ApplicationBar.MenuItems.Add(appBarItemAbout);
        }

        private void InfoLayer_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            this.InfoLayer.IsOpen = !this.InfoLayer.IsOpen;
        }
    }
}